package com.party.mobile.web.controller.copartner;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.party.authorization.annotation.Authorization;
import com.party.common.paging.Page;
import com.party.common.utils.PartyCode;
import com.party.core.exception.BusinessException;
import com.party.core.model.copartner.*;
import com.party.core.model.member.CopartnerAnalyzeQuery;
import com.party.core.service.copartner.IBrokerageItemService;
import com.party.core.service.copartner.ICopartnerLevelService;
import com.party.core.service.member.IMemberService;
import com.party.mobile.biz.copartner.CopartnerBizService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.biz.member.CopartnerMemberBizService;
import com.party.mobile.biz.member.MemberBizService;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.copartner.input.CeoRegisterInput;
import com.party.mobile.web.dto.copartner.input.CopartnerRegisterInput;
import com.party.mobile.web.dto.copartner.output.GetDateOutput;
import com.party.mobile.web.dto.copartner.output.ProjectCountOutput;
import com.party.mobile.web.dto.copartner.output.RepresentProjectListOutput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.login.output.MemberOutput;
import com.party.mobile.web.dto.member.input.BindPhoneInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 合伙人控制器
 * Created by wei.li.
 *
 * @date 2018/2/6 0006
 * @time 11:35
 */
@Controller
@RequestMapping(value = "copartner")
public class CopartnerController {

    @Autowired
    private MemberBizService memberBizService;

    @Autowired
    private CopartnerMemberBizService copartnerMemberBizService;

    @Autowired
    private CopartnerBizService copartnerBizService;

    @Autowired
    private CurrentUserBizService currentUserBizService;

    @Autowired
    private ICopartnerLevelService copartnerLevelService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IBrokerageItemService brokerageItemService;

    protected static Logger logger = LoggerFactory.getLogger(CopartnerController.class);

    /**
     * 注册联盟机构
     * @param input 输入参数
     * @param result 验证结果
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "register")
    public AjaxResult register(@Validated CopartnerRegisterInput input, BindingResult result){
        AjaxResult ajaxResult = new AjaxResult();

        //数据验证
        if (result.hasErrors()){
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription(description);
            return ajaxResult;
        }

        MemberOutput memberOutput;
        try {
            memberOutput = copartnerMemberBizService.register(input);
        }catch (BusinessException be){
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        }
        catch (Exception e) {
            ajaxResult.setDescription("系统异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(memberOutput);
        return ajaxResult;
    }

    /**
     * 获取数据
     *
     * @param id 编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "getDate")
    public AjaxResult getDate(String id){
        AjaxResult ajaxResult = new AjaxResult();
        GetDateOutput getDateOutput;
        try {
            getDateOutput = copartnerBizService.getDate(id);
        } catch (BusinessException be) {
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        }catch (Exception e){
            ajaxResult.setDescription("查询数据异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(getDateOutput);
        return ajaxResult;
    }


    /**
     * 联合发起的众筹列表
     * @param isSuccess 是否成功 1:是 2：不传默认是全部
     * @param representId 联合发起编号
     * @param page 分页参数
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "projectForRepresentList")
    public AjaxResult projectForRepresentList(Integer isSuccess, String representId, Page page){
        AjaxResult ajaxResult = new AjaxResult();

        //参数验证
        if (Strings.isNullOrEmpty(representId)){
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription("联合发起编号不能为空");
            return ajaxResult;
        }

        try {
            List<RepresentProjectListOutput> list = copartnerBizService.projectForRepresentList(isSuccess, representId, page);
            return AjaxResult.success(list, page);
        } catch (Exception e) {
            logger.error("查询众筹列表异常", e);
            ajaxResult.setDescription("查询众筹列表异常");
            return ajaxResult;
        }
    }


    /**
     * 联合发起众筹统计
     *
     * @param representId 联合发起编号
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "projectCount")
    public AjaxResult projectCount(String representId){
        AjaxResult ajaxResult = new AjaxResult();

        //参数验证
        if (Strings.isNullOrEmpty(representId)){
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription("联合发起编号不能为空");
            return ajaxResult;
        }

        ProjectCountOutput output;
        try {
            output = copartnerBizService.projectCount(representId);
        } catch (Exception e) {
            logger.error("联合发起众筹统计异常", e);
            ajaxResult.setDescription("查询异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(output);
        return ajaxResult;
    }


    /**
     * 更新合作商会员信息
     *
     * @param input 输入参数
     * @param result 验证参数
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "updateMember")
    public AjaxResult updateMember(@Validated CopartnerRegisterInput input, BindingResult result,
                                   BindPhoneInput bindPhoneInput, HttpServletRequest request){
        AjaxResult ajaxResult = new AjaxResult();

        //数据验证
        if (result.hasErrors()){
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            ajaxResult.setErrorCode(PartyCode.PARAMETER_ILLEGAL);
            ajaxResult.setDescription(description);
            return ajaxResult;
        }

        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        MemberOutput memberOutput;

        try {
            if(!Strings.isNullOrEmpty(bindPhoneInput.getMobile())) {
                //验证码验证
                memberBizService.bindPhoneBiz2(input.getMobile(), input.getVerifyCode(), input.getCountryCode(), request);
            }
            memberOutput = copartnerBizService.updateMember(input, currentUser.getId());
        }catch (BusinessException be){
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        }
        catch (Exception e) {
            logger.error("更新用户信息异常", e);
            ajaxResult.setDescription("更新用户异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(memberOutput);
        return ajaxResult;
    }

    /**
     * 合伙人首页
     *
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "copartnerIndex")
    public AjaxResult copartnerIndex(Page page, HttpServletRequest request){
        try {

            CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

            Map<String,Object> params = Maps.newHashMap();
            params.put("parentId", currentUser.getId());

            List<CopartnerLevelOutput> clolist = copartnerLevelService.copartnerList(params, page);
            return AjaxResult.success(clolist, page);
        } catch (Exception e) {
            logger.error("合伙人首页异常", e);
            return AjaxResult.error(100, "合伙人首页异常");
        }
    }


    /**
     * 注册合作渠道用户 v2
     *
     * @param input  输入参数
     * @param result 验证结果
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "/v2/register")
    public AjaxResult registerv2(@Validated CopartnerRegisterInput input, BindingResult result) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        try {
            MemberOutput memberOutput = copartnerMemberBizService.registerV2(input);
            return AjaxResult.success(memberOutput);
        } catch (BusinessException be) {
            logger.error(be.getMessage(), be);
            return AjaxResult.error(be.getCode(), be.getMessage());
        } catch (Exception e) {
            logger.error("ceo户外联盟注册异常", e);
            return AjaxResult.error(100, "系统异常");
        }
    }

    /**
     * 注册合作渠道用户 v3
     *
     * @param input  输入参数
     * @param result 验证结果
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "/v3/register", method = RequestMethod.POST)
    public AjaxResult registerV3(@Validated CeoRegisterInput input, BindingResult result) {
        //数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, description);
        }

        try {
            MemberOutput memberOutput = copartnerMemberBizService.registerV3(input);
            return AjaxResult.success(memberOutput);
        } catch (BusinessException be) {
            logger.error(be.getMessage(), be);
            return AjaxResult.error(be.getCode(), be.getMessage());
        } catch (Exception e) {
            logger.error("ceo户外联盟注册异常", e);
            return AjaxResult.error(100, "注册失败");
        }
    }


    /**
     * 获取已邀请合伙人和累计赚钱
     *
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "getPartnerAndMoney")
    public AjaxResult getPartnerAndMoney(HttpServletRequest request){
        AjaxResult ajaxResult = new AjaxResult();

        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);

        Map<String,Object> mmp = new HashMap<>();

        try {
            //下级人数
            CopartnerLevelInput input1 = new CopartnerLevelInput();
            input1.setMemberId(currentUser.getId());
            Integer invitePartnerNum=copartnerLevelService.getJuniorPartnersTotal(input1);

            invitePartnerNum = invitePartnerNum ==null? 0:invitePartnerNum;

            //我获取下级直接推广的
            CopartnerLevelInput input2 = new CopartnerLevelInput();
            input2.setParentId(currentUser.getId());
            Double  lowerMoney  = copartnerLevelService.getPromoteOrLowerToMoney(input2);

/*            //直接推广的
            CopartnerLevelInput input3 = new CopartnerLevelInput();
            input3.setPartnerId(currentUser.getId());
            Double promoteMoney = copartnerLevelService.getPromoteOrLowerToMoney(input3);


            double amountTotal = BigDecimalUtils.add(promoteMoney, lowerMoney);*/
            mmp.put("invitePartnerNum",invitePartnerNum);
            mmp.put("amountTotal",lowerMoney);
        }catch (BusinessException be){
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        }
        catch (Exception e) {
            logger.error("获取已邀请合伙人和累计赚钱异常", e);
            ajaxResult.setDescription("获取已邀请合伙人和累计赚钱异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData(mmp);
        return ajaxResult;
    }


    /**
     * 初始化分销关系表数据
     *
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "initDistributionBet")
    public AjaxResult initDistributionBet(HttpServletRequest request){
        AjaxResult ajaxResult = new AjaxResult();
        try {
            List<String> members=  memberService.getAllChannelDis();
            for(String s:members){
                CopartnerLevel c =  copartnerLevelService.findByMemberId(s);
                if (c == null) {
                    CopartnerLevel inc = new CopartnerLevel();
                    inc.setMemberId(s);
                    copartnerLevelService.insert(inc);
                }
            }

        }catch (BusinessException be){
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        }
        catch (Exception e) {
            logger.error("初始化分销关系表数据异常", e);
            ajaxResult.setDescription("初始化分销关系表数据异常");
            return ajaxResult;
        }
        ajaxResult.setSuccess(true);
        ajaxResult.setData("初始化成功");
        return ajaxResult;
    }

    /**
     * 我分得佣金
     *
     * @return 交互数据
     */
    @ResponseBody
    @Authorization
    @RequestMapping(value = "earningsDetailList")
    public AjaxResult earningsDetailList(String memberId,Page page, HttpServletRequest request) {
        AjaxResult ajaxResult = new AjaxResult();

        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        try {

            BrokerageItem brokerageItem = new BrokerageItem();
            brokerageItem.setPartnerId(memberId);
            brokerageItem.setParentId(currentUser.getId());

            List<BrokerageListOutput> list = brokerageItemService.adminlowerBrokerageDetailList(brokerageItem, new CopartnerAnalyzeQuery(), page);
            return AjaxResult.success(list, page);
        } catch (BusinessException be) {
            ajaxResult.setErrorCode(be.getCode());
            ajaxResult.setDescription(be.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("获取我分得佣金异常", e);
            ajaxResult.setDescription("获取我分得佣金异常");
            return ajaxResult;
        }
    }
}
